(ns clj-gallery.views.layout
  (:require [hiccup.page :refer :all]
            [hiccup.form :refer :all]
            [hiccup.element :refer [link-to]]
            [ring.util.response :refer [content-type response]]
            [compojure.response :refer [Renderable]]
            [selmer.parser :as parser]

            [clj-gallery.util :refer [login-user-id]]))

(def template-folder "templates/")

(defn utf-8-response [html]
  (content-type (response html) "text/html; charset=utf-8"))

(deftype RenderablePage [template params]
  Renderable
  (render [_ request]
    (->> (assoc params
           :context (:context request)
           :user (login-user-id))
         (parser/render-file (str template-folder template))
         utf-8-response)))

(defn render [template & [params]]
  (RenderablePage. template params))

#_(deftype RenderablePage [content]
    Renderable
    (render [_ request]
      (utf-8-response
        (html5
          [:head
           [:title "Welcome to picture-gallery"]
           (include-css "/css/screen.css")
           [:script {:type "text/javascript"}
            (str "var context = \"" (:context request) "\";")]
           (include-js "/js/jquery.min.js"
                       "/js/colors.js"
                       "/js/site.js")]
          [:body content]))))

(defn make-menu [& items]
  [:div#usermenu (for [item items] [:div.menuitem item])])

(defn guest-menu []
  (make-menu
    (link-to "/" "home")
    (link-to "/register" "register")
    (form-to [:post "/login"]
             (text-field {:placeholder "screen name"} "id")
             (password-field {:placeholder "password"} "pass")
             (submit-button "login"))))

(defn user-menu [user]
  (make-menu
    (link-to "/" "home")
    (link-to "/upload" "upload images")
    (link-to "/logout" (str "logout " user))
    (link-to "/delete-account" "delete account")))

(defn base [& content]
  #_(html5
      [:head
       [:title "Welcome to gallery"]
       (include-css "/css/screen.css")
       (include-js "//cdn.bootcss.com/jquery/3.1.1/jquery.min.js")]
      [:body content])
  #_(RenderablePage. content))

(defn common [& content]
  (base
    (if-let [user (login-user-id)]
      (user-menu user)
      (guest-menu))
    [:div.content content]))